import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}



// 导入组件,不写后面的文件，默认会找这个文件夹里的index.js或者index.vue
import login from '../views/login'
import layout from '../views/layout'
// 导入组件，并他们作为layout的子路由
import home from '../views/home'
import ask from '../views/ask'
import video from '../views/video'
import my from '../views/my'
import edit from '../views/my/edit'
import detail from '../views/detail'
import search from '../views/search'
import result from '../views/search/result'

const routes = [

  // 什么都不输的路径，直接跳转到layout/home路径
  { path: '/', redirect: '/layout/home' },
  // 路由是：网页路径 跟 某个组件的对应关系
  { name: 'login', path: '/login', component: login },
  { name: 'detail', path: '/article', component: detail },
  { name: 'search', path: '/search', component: search },
  { name: 'result', path: '/search/result', component: result },
  { 
    name: 'edit', 
    path: '/my/edit', 
    component: edit,
    meta: {
      needLogin: true
    } 
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      { name: 'home', path: 'home', component: home },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      {
        name: 'my',
        path: 'my',
        component: my,
        // 我给my这个路由打了一个标签
        // 标签上标记它需要登录才能访问
        meta: {
          needLogin: true
        }
      },
    ]
  },
]

const router = new VueRouter({
  routes
})


import store from '../store'
import { Toast } from 'vant';

// to：要去哪个路由
// from：从哪个路由来
// next: 是一个函数，调用它就代表放行，不调用就代表不放行
router.beforeEach((to, from, next) => {

  // 判断要去的路由是不是一个需要登录的路由
  if (to.meta.needLogin) {

    // 代表是需要登录才能访问的路由
    // 如何判断有没有登录？就判断有没有token
    if (store.state.tokenObj.token) {

      // 代表有token，就放行
      next()
    } else {
      // 代表没有token，没有token就意味着没登录
      // 那就要打回登录页
      Toast.fail('请先登录')
      next('/login') // 放行到login页

    }

  } else {
    // 不需要登录的路由直接放行
    next()
  }
})

export default router
